package com.njcb.ams;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

/**
 * 根据数据库表生成html增删改查页面
 *
 * @author liuyanlong
 */
public class MainHtml {
    static String ACTION_URL = "workoff/";
    static String DB_SCHEMA = "AMS";

    public static void main(String[] args) throws Exception {

        String tableName = "attr_list";
        String htmlName = "请假信息页面";
        MainHtml mh = new MainHtml();
        Connection conn = getConnection();
        String htmlStr = mh.genHtml(conn, tableName, htmlName);

        // 写入文件
        String htmlFilePath = "C:\\Users\\LOONG\\git\\fims\\src\\main\\resources\\static\\html\\";
        String htmlFileName = "workoff.html";
        WriteToFile(htmlFilePath, htmlFileName, htmlStr);

    }

    /**
     * @return
     * @throws SQLException
     */
    private static Connection getConnection() throws Exception {
        String url = "jdbc:oracle:thin:@trythis.cn:1521/xe";
        String drive = "oracle.jdbc.driver.OracleDriver";
        Properties prop = new Properties();
        prop.setProperty("user", "ams");
        prop.setProperty("password", "ams");
        prop.setProperty("remarks", "true");
        Class.forName(drive);
        Connection conn = DriverManager.getConnection(url, prop);
        return conn;
    }

    private List<Map<String, String>> getColumns(Connection conn,
                                                 String tableName) throws Exception {
        List<Map<String, String>> columns = new ArrayList<Map<String, String>>();
        DatabaseMetaData dbMetaData = conn.getMetaData();
        ResultSet rsColumns = null;
        try {
            rsColumns = dbMetaData.getColumns(null, DB_SCHEMA,
                    tableName.toUpperCase(), null);
            if (rsColumns == null) {
                throw new Exception("数据表[" + tableName + "]不存在");
            }
            while (rsColumns.next()) {
                Map<String, String> map = new HashMap<String, String>();
                String columnName = rsColumns.getString("COLUMN_NAME").trim()
                        .toUpperCase();
                if ("ID".equals(columnName)) {
                    continue;
                }
                String remarks = rsColumns.getString("REMARKS");
                if (null == remarks || remarks.trim().length() == 0) {
                    remarks = columnName;
                }
                // String typeName = rsColumns.getString("TYPE_NAME");
                // int dataType = rsColumns.getInt("DATA_TYPE");
                map.put("COLUMN_NAME", columnName);
                map.put("REMARKS", remarks);
                columns.add(map);
            }
        } finally {
            if (null != rsColumns) {
                rsColumns.close();
            }
            if (null != conn) {
                conn.close();
            }
        }
        return columns;
    }

    /***
     *
     * 方法功能描述：生成HTML页面代码
     *
     * @param conn
     * @param tableName
     * @param htmlName
     * @return
     * @throws Exception
     */
    private String genHtml(Connection conn, String tableName, String htmlName)
            throws Exception {
        List<Map<String, String>> columns = getColumns(conn, tableName);
        StringBuilder sb = new StringBuilder();
        sb.append("<!DOCTYPE html>\n");
        sb.append("<html>\n");
        sb.append("<head>\n");
        sb.append("<title>" + htmlName + "</title>\n");
        sb.append(
                "    <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n");
        sb.append("    <script type=\"text/javascript\">\n");
        sb.append("        var path = window.document.location.href;\n");
        sb.append(
                "        var pathName = window.document.location.pathname;\n");
        sb.append(
                "        var hostPath = path.substring(0, path.indexOf(pathName));\n");
        sb.append(
                "        var projectName = pathName.substring(0, pathName.substr(1).indexOf(\"/\") + 1);\n");
        sb.append(
                "        document.write('<scr' + 'ipt src=\"' + projectName + '/js/html/header.js\"></scr'+'ipt>');\n");
        sb.append("    </script>\n");
        sb.append("</head>\n");
        sb.append("<body>\n");
        sb.append(
                "	<table id=\"dg\" style=\"width: auto; height: auto\" fitColumns=\"true\">\n");
        sb.append("		<thead>\n");
        sb.append("			<tr>\n");
        sb.append(
                "			<th field=\"id\" data-options=\"hidden:true\">ID</th>\n");
        for (Map<String, String> column : columns) {
            String columnName = column.get("COLUMN_NAME");
            columnName = db2java(columnName);
            String remarks = column.get("REMARKS");
            sb.append("			<th field=\"" + columnName
                    + "\" align=\"right\" width=\"100\" \n");
            sb.append("				data-options=\"\n");
            sb.append("				sortable:true,\n");
            sb.append("				remoteSort:false\n");
            sb.append("				\">" + remarks + "</th>\n");
        }
        sb.append("			</tr>\n");
        sb.append("		</thead>\n");
        sb.append("	</table>\n");
        sb.append("	<div id=\"dg-buttons\" style=\"height: auto\">\n");
        sb.append("		<div style=\"margin-bottom:5px\">\n");
        sb.append(
                "			<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-add',plain:true\" 	onclick=\"dlgAdd()\">新增</a>\n");
        sb.append(
                "			<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-remove',plain:true\" 	onclick=\"dlgRemove()\">删除</a>\n");
        sb.append(
                "			<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" data-options=\"iconCls:'icon-edit',plain:true\" 	onclick=\"dlgEdit()\">修改</a>\n");
        sb.append("		</div>\n");
        sb.append("		<div>\n");
        sb.append(
                "			<span>&nbsp;&nbsp;&nbsp;&nbsp;选择:</span>\n");
        sb.append(
                "			<input type=\"text\" id=\"searchKey\" name=\"searchKey\" class=\"easyui-combobox\" />\n");
        sb.append("			<span>等于:</span>\n");
        sb.append(
                "			<input type=\"text\" id=\"searchValue\" name=\"searchValue\" class=\"easyui-validatebox\" />\n");
        sb.append(
                "			<a href=\"javascript:void(0)\" class=\"easyui-linkbutton\" iconCls=\"icon-search\" onclick=\"dgop.find()\">查询</a>\n");
        sb.append("		</div>\n");

        sb.append("	</div>\n");
        sb.append("<div id=\"dlg-buttons\">\n");
        sb.append(
                "		<a href=\"javascript:dlgSave()\" class=\"easyui-linkbutton\" iconCls=\"icon-ok\">保存</a>\n");
        sb.append(
                "		<a href=\"javascript:dlgClose()\" class=\"easyui-linkbutton\" iconCls=\"icon-cancel\">关闭</a>\n");
        sb.append("	</div>\n");
        sb.append(
                "	<div id=\"dlg\" class=\"easyui-dialog\" closed=\"true\" style=\"width: 730px; height: 380px; padding: 10px 10px;\" buttons=\"#dlg-buttons\">\n");
        sb.append("		<form method=\"post\" id=\"fm\">\n");
        sb.append("			<table cellspacing=\"8px;\">\n");
        sb.append(
                "				<td><input id=\"id\" name=\"id\" style=\"display: none\" ></td>\n");
        for (Map<String, String> column : columns) {
            String columnName = column.get("COLUMN_NAME");
            columnName = db2java(columnName);
            String remarks = column.get("REMARKS");
            sb.append("			<tr>\n");
            sb.append("				<td>" + remarks + "</td>\n");
            sb.append("				<td><input id=\"" + columnName
                    + "\" name=\"" + columnName
                    + "\" class=\"easyui-validatebox\" required=\"true\" \n");
            sb.append("					>&nbsp; \n");
            sb.append(
                    "					<span style=\"color: red\">*</span>\n");
            sb.append("				</td>\n");
            sb.append("			</tr>\n");
        }
        sb.append("			</table>\n");
        sb.append("		</form>\n");
        sb.append("	</div>\n");
        sb.append(
                "	<div id=\"dlg-Details\" class=\"easyui-window\" closed=\"true\" style=\"width: 730px; height: 280px; padding: 10px 10px;\"></div>\n");
        sb.append("	<script>\n");
        sb.append("		var initd = {\n");
        sb.append("			queryDataURL : \"/" + ACTION_URL
                + db2java(tableName) + "Query.do\",\n");
        sb.append("			saveDataURL : \"/" + ACTION_URL
                + db2java(tableName) + "Save.do\",\n");
        sb.append("			removeDataURL:\"/" + ACTION_URL
                + db2java(tableName) + "Remove.do\",\n");
        sb.append("			dg : $('#dg')\n");
        sb.append("		};\n");
        sb.append("	</script>\n");
        sb.append("</body>\n");
        sb.append("</html>\n");
        return sb.toString();
    }

    /**
     * 方法功能描述：数据库转换成java
     *
     * @param tableName
     * @return
     * @throws Exception
     */
    private String db2java(String tableName) throws Exception {
        tableName = tableName.toLowerCase();
        String[] keys = tableName.split("_");
        String columnName = "";
        for (int i = 0; i < keys.length; i++) {
            String key = keys[i];
            if (i != 0) {
                key = key.substring(0, 1).toUpperCase() + key.substring(1);
            }
            columnName = columnName + key;
        }
        return columnName;
    }

    /**
     * 方法功能描述：将HTML代码写入文件
     *
     * @param htmlFilePath
     * @param htmlFileName
     * @param htmlStr
     * @throws IOException
     */
    private static void WriteToFile(String htmlFilePath, String htmlFileName,
                                    String htmlStr) throws IOException {

        File file = new File(htmlFilePath + htmlFileName);

        if (file.exists()) {
            System.out.println("文件已经存在");
            return;
        }

        boolean isSucc = file.createNewFile();
        if (!isSucc) {
            System.out.println("文件创建失败");
            return;
        }
        System.out.println("文件创建成功");
        System.out.println("开始写入HTML代码到文件中");

        FileWriter fileWriter = new FileWriter(file.getAbsolutePath(), true);
        try {
            fileWriter.write(htmlStr);
            fileWriter.flush();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e1) {
                }
            }
        }

        System.out.println("写入HTML代码完成");

    }

}
